package de.ret_world.openrpgstudio.engine.artemis.systems;

import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.EntityProcessingSystem;
import com.artemis.utils.Bag;
import de.ret_world.openrpgstudio.engine.GameState;
import de.ret_world.openrpgstudio.engine.artemis.components.Location;
import de.ret_world.openrpgstudio.engine.artemis.components.SkinComponent;
import org.jrabbit.base.graphics.layers.grouped.DefaultLayeredRenderList;
import org.jrabbit.standard.game.managers.GameManager;
import org.jrabbit.standard.game.objects.Sprite;

/**
 *
 * @author Emu
 */
public class RenderSystem extends EntityProcessingSystem {

    private ComponentMapper<SkinComponent> skinComponentMapper;
    private ComponentMapper<Location> locationMapper;
    private Bag<Sprite> sprites;
    private DefaultLayeredRenderList renderList;

    public RenderSystem() {
        super(Location.class, SkinComponent.class);

        sprites = new Bag<>();
        renderList = new DefaultLayeredRenderList();
    }

    @Override
    protected void initialize() {
        skinComponentMapper = new ComponentMapper<>(SkinComponent.class, world);
        locationMapper = new ComponentMapper<>(Location.class, world);
    }

    @Override
    protected void begin() {
        super.begin();
        renderList.clear();
    }

    @Override
    protected void process(Entity e) {
        Sprite sprite = sprites.get(e.getId());
        Location loc = locationMapper.get(e);

        Object currentMap = GameState.getVariable("CurrentMap");
        if (currentMap != null && String.class.isInstance(currentMap)) {
            if (loc.getMapID().equals((String) currentMap)) {

                if (!renderList.contains(loc.getLayerID())) {
                    renderList.add(loc.getLayerID());
                }

                if (GameManager.camera().views(loc.getPoint().getX(), loc.getPoint().getY(), 50)) {
                    sprite.location().set(loc.getPoint().getX(), loc.getPoint().getY());
                    renderList.add(sprite, loc.getLayerID());
                }
            }
        }
    }

    @Override
    protected void end() {
        super.end();
        renderList.render();
    }

    @Override
    protected void added(Entity e) {
        SkinComponent skincomp = skinComponentMapper.get(e);
        Sprite sprite = new Sprite(skincomp.getSkin());
        if (sprite != null) {
            sprites.set(e.getId(), sprite);
        }
    }

    @Override
    protected void removed(Entity e) {
        sprites.set(e.getId(), null);
    }
}
